import { _decorator, AudioClip, AudioSource, Component, Node } from 'cc';
import { BundleManager } from './BundleManager';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager extends Component {
    public static AudioSource: AudioSource = null;
    public static AudioClipName: string[] = ["BGM", "婴儿哭", "按钮点击"];
    public static AudioMap: Map<string, AudioClip>;
    public static AudioSourceMap: Map<string, AudioSource>;
    /**
     * 播放全局音效
     */
    public static globalAudioPlay(AudioName: string) {
        AudioManager.AudioSource.playOneShot(AudioManager.AudioMap.get(AudioName));
    }
    /**
     * 播放音效
     * @param AudioName 想要播放的音频文件名
     * @param AudioManager 播放的音频控制器
     */
    public static AudioPlay(AudioName: string, distance: number) {
        let num = (200 - distance) / 200;
        if (num < 0) {
            num = 0;
        }
        AudioManager.AudioSource.playOneShot(AudioManager.AudioMap.get(AudioName), num);
    }

    public static playLookAudio(AudioName: string) {
        if (AudioManager.AudioSourceMap.has(AudioName)) {
            //库中存在
            if (AudioManager.AudioSourceMap.get(AudioName).playing) {
                return;
            } else {
                AudioManager.AudioSourceMap.get(AudioName).play();
            }
        } else {//库中没有存在改音效的控制器
            let audio = new AudioSource();
            audio.clip = AudioManager.AudioMap.get(AudioName);
            audio.loop = true;
            audio.play();
            AudioManager.AudioSourceMap.set(AudioName, audio);
        }
    }

    public static StopLoopAudio(AudioName: string) {
        if (AudioManager.AudioSourceMap.has(AudioName)) {
            AudioManager.AudioSourceMap.get(AudioName).stop();
        }
    }

    //初始化所有声音文件
    public static Init() {
        AudioManager.AudioSourceMap = new Map<string, AudioSource>();
        AudioManager.AudioMap = new Map<string, AudioClip>();
        AudioManager.AudioClipName.forEach((name) => {
            BundleManager.GetBundle("Audio").load(name, AudioClip, (err, data) => {
                if (err) {
                    console.log("没有找到音频资源" + name);
                    return;
                }
                AudioManager.AudioMap.set(name, data);
            })
        })

    }

}


